package com.itheima.service.impl;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.LoginDTO;
import com.itheima.common.entity.Result;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.time.LocalDate;
import java.util.List;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 手机验证码登录
     * @param loginDTO
     * @return
     */
    @Override
    public Result login(LoginDTO loginDTO) {
        if (loginDTO.getTelephone()==null || loginDTO.getValidateCode()==null){  //不能传空
            return new Result(false,MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL,null);
        }
        if (redisTemplate.hasKey(loginDTO.getTelephone())){  //如果存在redis中
            String code =(String) redisTemplate.opsForValue().get(loginDTO.getTelephone()); //获取验证码
            if (loginDTO.getValidateCode().equals(code)){ //短信验证成功
                //检查是否为会员
                List<Member> memberList= memberDao.findByPhoneNumber(loginDTO.getTelephone());
                if (memberList==null && memberList.size()==0){  //不是会员就自动注册会员
                    Member member=new Member();
                    member.setPhoneNumber(loginDTO.getTelephone());
                    member.setRegTime(Date.valueOf(LocalDate.now()));
                    member.setName(loginDTO.getTelephone());
                    memberDao.insert(member);
                }
            }else {  //短信验证错误
                return new Result(false,MessageConstant.VALIDATECODE_ERROR,null);
            }
        }else { //不存在则表示短信发送失败
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL,null);
        }
        //返回成功
        return new Result(true ,MessageConstant.LOGIN_SUCCESS,null);
    }
}
